package com.yeyks.app.function.rocketmq.consumer;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.google.common.collect.ImmutableMap;
import com.yeyks.common.constants.ConfigKey;
import com.yeyks.common.dto.mq.CToAppMessage;
import com.yeyks.common.dto.mq.WebToCSendMessage;
import com.yeyks.commonReference.append.getui.service.AppServerGeTuiService;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.commonReference.service.other.ActivityInfoService;
import com.yeyks.consumer.dal.domain.MessageNotice;
import com.yeyks.consumer.service.MessageNoticeService;
import com.yeyks.other.dal.domain.ActivityInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息推送（例如活动推送）
 *
 * @author shuai
 * @date 2019/12/02 16:06
 */
@Slf4j
@Component
public class WebToCSendMessageListener implements MessageListener {

    @Autowired
    private AppServerGeTuiService appServerGeTuiService;
    @Autowired
    private ActivityInfoService activityInfoService;
    @Autowired
    private MessageNoticeService noticeService;
    @Autowired
    private ConfigService configService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            Long startTime = System.currentTimeMillis();
            byte[] body = message.getBody();
            //获取到接收的消息，由于接收到的是byte数组，所以需要转换成字符串
            String msg = new String(body);
            //处理业务逻辑
            disposeLogic(msg);
            log.info("消息推送检测：监听到的消息：message = {}", msg);
            Long endTime = System.currentTimeMillis();
            log.info("消息推送检测：单次消费耗时：" + (endTime - startTime) / 1000);
        } catch (Exception e) {
            log.error("MessageListener.consume error:" + e.getMessage(), e);
        }
        return Action.CommitMessage;
    }

    /**
     * 消息推送处理业务逻辑
     *
     * @param msg 监听到的信息
     */
    private void disposeLogic(String msg) {
        try {
            WebToCSendMessage webSocket = JSONUtil.toBean(msg, WebToCSendMessage.class);
            if (null != webSocket) {
                pushWebToCSend(webSocket);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送检测：处理监听消息异常：msg = {}", msg);
        }
    }

    /**
     * 个推(消息推送)
     *
     * @param webSocket 对象信息
     */
    private void pushWebToCSend(WebToCSendMessage webSocket) {
        //活动消息推送
        if (1 == webSocket.getType()) {
            if (StrUtil.isBlank(webSocket.getId())) {
                log.info("该活动消息推送消息为空msg = {}", webSocket);
                return;
            }
            ActivityInfo activityInfo = activityInfoService.getById(webSocket.getId());
            if (ObjectUtil.isNull(activityInfo)) {
                log.info("该活动不存在活动id = {}", webSocket.getId());
                return;
            }
            if (1 != activityInfo.getType()) {
                log.info("该活动非url链接不推送，活动id = {}", webSocket.getId());
                return;
            }
            if (activityInfo.getId() != null && activityInfo.getTitle() != null && activityInfo.getContent() != null) {
                createMessage(activityInfo);
                //设置消息对象
                CToAppMessage cToAppMessage = new CToAppMessage();
                cToAppMessage.setType(20);
                cToAppMessage.setTitle(activityInfo.getTitle());
                cToAppMessage.setContent(activityInfo.getContent());
                appServerGeTuiService.allPush(activityInfo.getTitle(), JSONUtil.toJsonStr(cToAppMessage));
            }
        }
    }

    private void createMessage(ActivityInfo activityInfo) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("content", activityInfo.getContent());
            map.put("iconUrl", getActivityIcon());
            map.put("title", activityInfo.getTitle());
            noticeService.activieyIdCreateAndSave(map, activityInfo.getId().intValue(), MessageNotice.Type.activity_activity.value());
        } catch (Exception e) {
            log.error("创建活动消息失败异常{}", e.getLocalizedMessage());
            e.printStackTrace();
        }
    }

    private String getActivityIcon() {
        try {
            String value = configService.getValue(ConfigKey.ACTIVITY_ICON);
            if (value != null) {
                return value;
            }
            return "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/Public/testicon.png";
        } catch (Exception e) {
            log.error("个推发送消息获取活动icon异常{}", e.getLocalizedMessage());
            e.printStackTrace();
            return "http://yeyu-kuaisu.oss-cn-hangzhou.aliyuncs.com/Public/testicon.png";
        }
    }
}
